<?php

/*
	PIE Content Management System
	John Girata
	Licensed under the GNU General Public License version 3
*/

defined('PIESECVAR') or die('Restricted Access');

class LoginHandler
{
	// For security reasons, this is read-only
	private $login = false;
	
	function __construct()
	{
		// If the username and cookie variables are set, check the information against that in the DB
		if(isset($_COOKIE['username']) && strlen($_COOKIE['username']) > 0 && isset($_COOKIE['password']) && strlen($_COOKIE['password']) > 0)
			$this->check_login($_COOKIE['username'], $this->db_encrypt($this->cookie_decrypt($_COOKIE['password'])));
	}
	
	function check_login($username, $password, $set_login_vars = true)
	{
		global $db, $controller;
		
		$db->rescape($username);
		$db->rescape($password);
		
		$db->query("SELECT * FROM `#__users` WHERE `username`='$username' AND `password`='$password' LIMIT 1");
		
		if($db->get_num_rows() == 1)
		{
			if($set_login_vars)
			{
				$info = $db->get_array();
				$info = $info[0];
				$info['groups'] = explode(',', $info['groups']);
				
				$this->login = $info;
			}
			
			return true;
		}
		else
		{
			if($set_login_vars)
				$this->login = false;
			return false;
		}
	}
	
	function get_login()
	{
		return $this->login;
	}
	
	function logout()
	{
		$this->login = false;
		return true;
	}
	
	function get_login_attr($attr)
	{
		if(!$this->login)
			return false;
		
		if(isset($this->login[$attr]))
			return $this->login[$attr];
		else
			return false;
	}
	
	function db_encrypt($raw)
	{
		return sha1($raw);
	}
	
	function cookie_encrypt($raw)
	{
		return $_SERVER['REMOTE_ADDR'] . '%' . $raw;
	}
	
	function cookie_decrypt($encrypted)
	{
		$parts = explode('%', $encrypted);
		$ip = array_shift($parts);
		
		if(strcasecmp($ip, $_SERVER['REMOTE_ADDR']) != 0)
			return false;
		
		if(count($parts) > 1)
			return implode('', $parts);
		else
			return $parts[0];
	}
}

?>